package com.zhanghe.security.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class JwtUtil {

    protected static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     *
     * 功能：生成 jwt token<br/>
     * @param name	实例名
     * @param param	需要保存的参数
     * @param secret	秘钥
     * @param expirationtime	过期时间(5分钟 5*60*1000)
     * @return
     * @exception   无
     * @since   	首次创建（zhanghe  2018-3-27)<br/>
     *
     */
    public static String sign(String name,Map<String,Object> param,String secret,Long expirationtime){
        String JWT = Jwts.builder()
                .setClaims(param)
                .setSubject(name)
                .setExpiration(new Date(System.currentTimeMillis() + expirationtime))
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
        return JWT;
    }
    /**
     *
     * 功能：解密 jwt<br/>
     * @param JWT	token字符串
     * @param secret	秘钥
     * @return
     * @exception   无
     * @since   	首次创建（zhanghe  2018-3-27)<br/>
     *
     */
    public static Claims verify(String JWT,String secret){
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(JWT)
                .getBody();
        return claims;
    }
    /**
     * 从token中取出subject
     * @param JWT
     * @param secret
     * @return
     */
    public static Object getSubject(String JWT,String secret){
        Claims claims = verify(JWT,secret);
        return claims.getSubject();
    }
    /**
     * 从token中取出某个属性值
     * @param JWT
     * @param secret
     * @param key
     * @return
     */
    public static Object getValue(String JWT,String secret,String key){
        Claims claims = verify(JWT,secret);
        return claims.get(key);
    }

    public static void main(String[] args){
        Map<String,Object> params = new HashMap<String,Object>(10);
        List<String> roles = new ArrayList<String>();
        roles.add("ROLE_ADMIN");

        params.put("roles",roles);
        String token = sign("6",params,"sdasfsdgfdsgsd",6000000000L);
        System.out.format("token:%s",token);
        System.out.println();
        System.out.format("subject:%s",getSubject(token,"sdasfsdgfdsgsd"));
        System.out.println();

        String refreshToken = sign("6",new HashMap<>(10),"sdasfsdgfdsgsd",60000000L);
        System.out.format("refreshToken:%s",refreshToken);
        System.out.println();
        System.out.format("subject:%s",getSubject(refreshToken,"sdasfsdgfdsgsd"));
    }

}
